package com.jingsu;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.opencv.core.Core;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Removebg {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }


    public final  static List<Cookie> cache = new ArrayList<>();

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.MINUTES)
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                    //内存中缓存Cookie
                    cache.addAll(list);
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    //过期的Cookie
                    List<Cookie> invalidCookies = new ArrayList<>();
                    //有效的Cookie
                    List<Cookie> validCookies = new ArrayList<>();

                    for (Cookie cookie : cache) {

                        if (cookie.expiresAt() < System.currentTimeMillis()) {
                            //判断是否过期
                            invalidCookies.add(cookie);
                        } else if (cookie.matches(url)) {
                            //匹配Cookie对应url
                            validCookies.add(cookie);
                        }
                    }

                    //缓存中移除过期的Cookie
                    cache.removeAll(invalidCookies);

                    //返回List<Cookie>让Request进行设置
                    return validCookies;
                }
            })
            .build();

    public static final String USERAGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, lko) Chrome/81.0.4044.129 Safari/537.36";

    public static void main1(String... args) throws Exception {
        Path dir = Paths.get("C:\\Users\\heike\\data\\images_complete\\product_images_new");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());


            try {

                File out = new File(file.getParent(), com.google.common.io.Files.getNameWithoutExtension(file.getName()) + ".png");

                if ( out.exists() ) {
                    return;
                }
                com.google.common.io.Files.copy(file, new File("out", file.getName()));

               // test(file, out);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("\t" + e.getMessage());
            }

        }
    }


    public static void main(String[] args) throws IOException {



        Request request1 = new Request.Builder()
                .url("https://www.remove.bg/zh/upload")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36")
                .build();

        try (Response response = client.newCall(request1).execute()) {
            String html = response.body().string();


            for (String s : response.headers().names()) {
                System.out.println(s + "  <==>  " + response.header(s));
            }

            Document doc = Jsoup.parse(html);


            Element token = doc.selectFirst("meta[name='csrf-token']");

            System.out.println("token: " + token.attr("content"));

           final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


            RequestBody body = RequestBody.create(JSON, "");

            Request request = new Request.Builder()
                    .url("https://www.remove.bg/trust_tokens")
                    .post(body)
                    .addHeader("x-csrf-token", token.attr("content"))
                    .addHeader("x-requested-with", "XMLHttpRequest")
                    .addHeader("origin", "https://www.remove.bg")
                    .addHeader("referer", "https://www.remove.bg/zh/upload")

                    .build();
            try (Response response1 = client.newCall(request).execute()) {

                System.out.println(response1.body().string());
            }

        }


//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("image_file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
//                .build();
//
//        Request request = new Request.Builder()
//                .header("X-Api-Key", "EedsELTidxA5JqZgUuddNPQ9")
//                .url("https://api.remove.bg/v1.0/removebg")
//                .post(requestBody)
//                .build();
//
//        Response response = client.newCall(request).execute();
//        if (!response.isSuccessful()) {
//            throw new IOException("Unexpected code " + response);
//        }


    }

}
